﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class NewsDAL : UKNowBaseDAL, IDALNews
    {
        private const string TBL_NAME               = "UKNOW_NEWS";
        private const string COL_LANG_ID            = "COL_LANG_ID";
        private const string COL_NEWS_ID            = "COL_NEWS_ID";
        private const string COL_NEWS_STATE         = "COL_NEWS_STATE";
        private const string COL_NEWS_TITLE         = "COL_NEWS_TITLE";
        private const string COL_NEWS_DESC          = "COL_NEWS_DESC";
        private const string COL_NEWS_CONTENT       = "COL_NEWS_CONTENT";
        private const string COL_NEWS_IS_HOTSPOT    = "COL_NEWS_HOTSPOT";
        private const string COL_NEWS_IMG_NAME      = "COL_NEWS_IMG_NAME";
        private const string COL_NEWS_IMG_PATH      = "COL_NEWS_IMG_PATH";
        private const string COL_NEWS_IMG_TYPE      = "COL_NEWS_IMG_TYPE";
        private const string COL_NEWS_IMG_DESC      = "COL_NEWS_IMG_DESC";
        /// <summary>
        /// 代码添加
        /// 修改时间 : 2012-03-14
        /// 修改人:穆凤凤
        /// 添加描述:新增 模板ID常量 
        /// </summary>
        private const string COL_NEWS_TEMPLATE_ID = "COL_NEWS_TEMPLATE_ID";//mff

        private const string COL_NEWS_INSERT_TIME   = "COL_NEWS_INSERT_TIME";
        private const string COL_NEWS_UPDATE_TIME   = "COL_NEWS_UPDATE_TIME";
        private const string COL_NEWS_COLUMN_ID = "COL_NEWS_COLUMN_ID";

        /// <summary>
        /// 2012-04-30 22:45 手机内容，用于接口 李学明 
        /// </summary>
        private const string COL_NEWS_PhoneContent = "COL_NEWS_PhoneContent";

        /// <summary>
        /// 2012-7-12 排序字段 李学明
        /// </summary>
        private const string COL_NEWS_Order = "COL_NEWS_Order";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(NewsModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_NEWS_ID, DataType.Int)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_NEWS_STATE, DataType.Int)); } }
        public IField Title { get { return FieldFactory.Create(ModelType, "Title", ColumnFactory.CreateColumn(COL_NEWS_TITLE, DataType.String, 200)); } }
        public IField ShortDescription { get { return FieldFactory.Create(ModelType, "ShortDescription", ColumnFactory.CreateColumn(COL_NEWS_DESC, DataType.String, 200)); } }
        public IField Content { get { return FieldFactory.Create(ModelType, "Content", ColumnFactory.CreateColumn(COL_NEWS_CONTENT, DataType.NText)); } }
        public IField IsHotspot { get { return FieldFactory.Create(ModelType, "IsHotspot", ColumnFactory.CreateColumn(COL_NEWS_IS_HOTSPOT, DataType.Bit)); } }
        public IField ImageName { get { return FieldFactory.Create(ModelType, "ImageName", ColumnFactory.CreateColumn(COL_NEWS_IMG_NAME, DataType.String, 200)); } }
        public IField ImagePath { get { return FieldFactory.Create(ModelType, "ImagePath", ColumnFactory.CreateColumn(COL_NEWS_IMG_PATH, DataType.String, 200)); } }
        public IField ImageType { get { return FieldFactory.Create(ModelType, "ImageType", ColumnFactory.CreateColumn(COL_NEWS_IMG_TYPE, DataType.String, 20)); } }
        public IField ImageDesc { get { return FieldFactory.Create(ModelType, "ImageDesc", ColumnFactory.CreateColumn(COL_NEWS_IMG_DESC, DataType.String, 500)); } }

        public IField TemplateID { get { return FieldFactory.Create(ModelType, "TemplateID", ColumnFactory.CreateColumn(COL_NEWS_TEMPLATE_ID, DataType.Int)); } }//mff
        public IField ColumnID { get { return FieldFactory.Create(ModelType, "ColumnID", ColumnFactory.CreateColumn(COL_NEWS_COLUMN_ID, DataType.Int)); } }
       
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_NEWS_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_NEWS_UPDATE_TIME, DataType.DateTime)); } }

        public IField PhoneContent { get { return FieldFactory.Create(ModelType, "PhoneContent", ColumnFactory.CreateColumn(COL_NEWS_PhoneContent, DataType.NText)); } }

        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_NEWS_Order, DataType.Int)); } }

        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, State, Title, ShortDescription, Content, IsHotspot, ImageName, ImagePath, ImageType, ImageDesc, TemplateID, InsertedTime, UpdatedTime, ColumnID, PhoneContent, Order }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return InsertFields; } }

        public NewsDAL() { }

        public NewsDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        #region IDALNews Members

        public NewsModel GetNewsModelByID(int? id)
        {
            NewsModel model = (NewsModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            return model;
        }

        public IList<NewsModel> GetAllNewsModels()
        {
            /*修改人：穆凤凤
       * 修改时间：2012-03-28
       * 修改内容：
       *      添加查询新闻的条件,whereClause,获得所有中文或英文的新闻纪录
       *      有mff注释的为本次修改的代码
       */
            string whereClause = string.Format("where {0}={1}", COL_LANG_ID, (int)this.Language.LanguageType);//mff
            return GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<NewsModel>().ToList();
        }
        /*修改人：穆凤凤
       * 修改时间：2012-03-13
       * 修改内容：
       *      新增实现接口的方法 获得按新闻标题或发布状态查找出来的活动新闻实体 GetNewsModelByTittle
       *      有mff注释的为本次修改的代码
       */
        //根据新闻标题或发布状态查找条件,获得新闻的记录
        //mff
        public IList<NewsModel> GetNewsModelByTittle(string newTittle, int? state)
        {
            StringBuilder stb = new StringBuilder();
            stb.AppendFormat("where COL_LANG_ID={0} and COL_NEWS_TITLE like '%{1}%' ", ((int)this.Language.LanguageType).ToString(), newTittle.Replace("'", "''")
);
            if (state == 0)
            {
                stb.AppendFormat("and  COL_NEWS_STATE={0}", state);
            }
            else
            {
                if (state == 1)
                {
                    stb.AppendFormat("and  COL_NEWS_STATE={0}", state);
                }
                else
                { stb.Append("and  COL_NEWS_STATE in (0,1)"); }

            }
            string whereClause = stb.ToString();
            IList<NewsModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(ID.PropertyName, SortOrder.Asc))).List.Cast<NewsModel>().ToList();
            //foreach (NewsModel model in models)
            //    SetForeignKeyModel(model); 用于涉及到多个表的字段的显示
            return models;
        }
        //mff

        public IList<NewsModel> GetPublishedNewsModels()
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_NEWS_STATE, 1, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            return GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<NewsModel>().ToList();
        }

        public ResultInfo Save(NewsModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_NEWS_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将新闻状态置为未发布
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "新闻数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存新闻数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
                        
                    trans.Commit();
                    result.Result = true;
                    result.Message = "新闻数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除新闻数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo SetHotspot(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.IsHotspot };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_NEWS_ID, DataType.Int, ids));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "将新闻设置成为热点新闻成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("设置热点新闻时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_NEWS_ID, DataType.Int, ids));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "新闻发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布新闻时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_NEWS_ID, DataType.Int, ids));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "新闻取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布新闻时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        #endregion

        #region 获取数据
        /// <summary>
        /// news列表分页 李学明最新修改，按照ID的倒序
        /// </summary>
        /// <param name="pagingParams">分页参数</param>
        /// <returns>返回PagingList</returns>
        public PagingList GetAllNewsByPaging(PagingParameter pagingParams)
        {
            WhereClauseBuilder buider = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            buider.Conditions.Add(CommonSearchCondition.CreateInstance(COL_NEWS_STATE,1,SearchConditionOperator.Equals));
            buider.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            string whereClause = buider.ToSqlCommand();
            if (pagingParams == null)
                pagingParams = PagingParameterFactory.CreateNonPagingParameter(null);

            if (pagingParams.SortingParameter == null)  //如果没有排序参数，默认按照最后更新时间倒排序
                pagingParams.SortingParameter = SortingParameterFactory.CreateInstance(Order.PropertyName, SortOrder.Asc);
           return GetModels(whereClause, pagingParams);
        }

       

        /// <summary>
        /// 获取新闻对应的手机图片
        /// </summary>
        /// <param name="nid">新闻ID</param>
        /// <returns></returns>
        public IList<PhoneImage> GetNewsPhone(int? nid)
        {
            if (!nid.HasValue)
                return null;
            string sql =
                string.Format(
                    "select COL_IMAGE_NAME as Imagename, COL_IMAGE_PATH as Imagpath,COL_IMAGE_THUMB_PATH as Thumbpath  from UKNOW_NEWS_PHONE_IMAGE where COL_NEWS_ID={0} and COL_LANG_ID={1} and COL_IMAGE_STATE=1",
                    nid, (int)this.Language.LanguageType);
            DataSet ds = DBHelper.ExecuteDataSet(sql, null);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].ToList<PhoneImage>();
            }
            return null;

        }

        #endregion

        public DataTable GetAllList()
        {
            string sqlcmd = @"select a.COL_MAPPING_ID,
                                    a.COL_DATA_ID_CN ,
                                    b.COL_NEWS_TITLE as COL_EVENTS_TITLE,
                                    a.COL_DATA_ID_EN,
                                    c.COL_NEWS_TITLE as COL_EVENTS_TITLE_EN
                                    from UKNOW_LANG_MAPPING  as a
                 left join UKNOW_NEWS  as b on a.COL_DATA_ID_CN=b.COL_NEWS_ID and b.COL_LANG_ID=2052 left join UKNOW_NEWS 
                 as c on a.COL_DATA_ID_EN=c.COL_NEWS_ID and c.COL_LANG_ID=1033
                 where a.COL_DATA_TYPE=2";

            DataSet ds = DBHelper.ExecuteDataSet(sqlcmd, null);

            if (ds != null)
            {
                DataTable dt = ds.Tables[0];
                return dt;
            }
            else
            {
                return null;
            }
           
          
        }

    }
}
